package controller;

import java.util.HashMap;

import controller.handstates.AbstractState;
import controller.handstates.PreFlopState;
import model.CommandQueue;
import model.Deck;
import model.HandChain;
import model.Player;
import model.Card;
import model.GameChain;
import model.Table;
import model.timers.BlindCounter;


public class HandController {
	
	private Deck deck;
	private Table table;
	protected HandChain handChain;
	
	private AbstractState handState;
	
	//public HandChain(HashMap<Integer, Player> playerChain){
	public HandController(HandChain handChain){
		this.handChain = handChain;		
		this.table = new Table(handChain.copy());
		this.deck = new Deck();	
	}	
	
	
	
	public void playHand(BlindCounter blinds){			
		// Play the hand
		handState = new PreFlopState(handChain, table, blinds, deck);
		CommandQueue q = new CommandQueue();
		while(handState != null){
			CommandManager.setState(handState, q);
			handState.setQueue(q);
			handState.playState();			
			handState = handState.getNextState();
		}
		
		// Hand is over, determine winners and hand out the money.
		handCleanup();
	}	
	
	protected void handCleanup(){
		int amountOnTable = 0;
		
		// take all the chips on the table
		for(Player p : table.getPlayers()){
			amountOnTable += p.getChipsOnTable();
			p.takeChipsOnTable();
		}
		
		// Award the chips appropriately
		if(handChain.size() == 1){
			Player p = handChain.getNextPlayer();
			p.addChips(amountOnTable);
			System.out.println("Awarding Player " + p.getSeat() + " with " + amountOnTable + " chips.");
		} else {
			// Everyone gets this amount ideally
			int equalShare = amountOnTable / handChain.size();
					
			for(Player p : handChain.getPlayers()){
				p.addChips(equalShare);
				amountOnTable -= equalShare;
			} 
			
			while(amountOnTable > 0){
				for(Player p : handChain.getPlayers()){
					if(amountOnTable > 0){
						p.addChips(1);
						amountOnTable -= 1;
						System.out.println("Awarding Player " + p.getSeat() + " with " + equalShare+1 + " chips.");
					}else {
						System.out.println("Awarding Player " + p.getSeat() + " with " + equalShare + " chips.");
					}
				}
			}
		}
	}
}
